// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.MonthlyCostReportReal;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.MonthlyCostReportRealMapper;
import com.fowo.api.model.monthly.cost.report.real.MonthlyCostReportRealCarryOverAction;
import com.fowo.api.model.monthly.cost.report.real.MonthlyCostReportRealExcelPo;
import com.fowo.api.model.monthly.cost.report.real.MonthlyCostReportRealItemVo;
import com.fowo.api.model.monthly.cost.report.real.MonthlyCostReportRealSearchParamPo;
import com.fowo.api.model.monthly.cost.report.real.MonthlyCostReportRealVo;
import com.fowo.api.service.MonthlyCostReportRealService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 成本月报 服务实现类
 * @author 蜂窝蜜造平台 配置人：蜂窝软件，沈友谅
 */
@Service
@Slf4j
@DataObjectType(MonthlyCostReportReal.class)
@DS("ds24")
public class MonthlyCostReportRealServiceImpl
  extends ServiceImpl<MonthlyCostReportRealMapper, MonthlyCostReportReal>
  implements MonthlyCostReportRealService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("periodIdAccperiodMonth", "ba.`accperiod_month`");
      put("stockIdName", "w.`name`");
      put("itemIdName", "p.`name`");
      put("sku", "p.`sku`");
      put("shopIdShopName", "si.`shop_name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected MonthlyCostReportRealService self;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected MonthlyCostReportRealCarryOverAction monthlyCostReportRealCarryOverAction;

  @Resource
  protected Validator validator;

  /**
   * 创建成本月报
   * @param model 成本月报
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(MonthlyCostReportRealVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReportReal entity = new MonthlyCostReportReal();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("成本月报保存失败");
  }

  /**
   * 更新成本月报
   * @param model 成本月报
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(MonthlyCostReportRealVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReportReal entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本月报不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "periodId",
      "stockId",
      "itemId",
      "sku",
      "shopId",
      "orgId",
      "stockAmount",
      "stockQty",
      "stockOutAmount",
      "stockOutQty",
      "stockInAmount",
      "stockInQty",
      "beginAmount",
      "beginQty",
      "lastUpdateUser",
      "lastUpdateTime",
      "createUser",
      "createTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新成本月报（带空值）
   * @param model 成本月报
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(MonthlyCostReportRealVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReportReal entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本月报不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        MonthlyCostReportReal::getCurrentIssueCostAmount,
        model.getCurrentIssueCostAmount()
      )
      .set(MonthlyCostReportReal::getLastUpdateUser, model.getLastUpdateUser())
      .set(MonthlyCostReportReal::getLastUpdateTime, model.getLastUpdateTime())
      .eq(MonthlyCostReportReal::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    MonthlyCostReportRealSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除成本月报
   * @param id 成本月报的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除成本月报
   * @param ids 成本月报的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    MonthlyCostReportRealSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "periodId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MonthlyCostReportRealItemVo) r).getPeriodIdAccperiodMonth()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "stockId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((MonthlyCostReportRealItemVo) r).getStockIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "itemId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((MonthlyCostReportRealItemVo) r).getItemIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shopId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((MonthlyCostReportRealItemVo) r).getShopIdShopName()
            )
          )
      );
      exportOptions.addStringFields(
        "periodIdAccperiodMonth",
        "stockIdName",
        "itemIdName",
        "sku",
        "shopIdShopName"
      );

      String fileName = String.format(
        "成本月报(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<MonthlyCostReportRealExcelPo> items =
      new ArrayList<MonthlyCostReportRealExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<MonthlyCostReportRealItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<MonthlyCostReportRealItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (MonthlyCostReportRealItemVo item : list) {
        MonthlyCostReportRealExcelPo excel = new MonthlyCostReportRealExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "成本月报(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(MonthlyCostReportRealExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过组织内码查询成本月报主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrgId(Long orgId) {
    return this.baseMapper.getIdByOrgId(orgId);
  }

  /**
   * 通过组织内码查询成本月报多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrgId(List<Long> list) {
    return this.baseMapper.getIdsByOrgId(list);
  }

  /**
   * 通过成本月报主键查询组织内码
   */
  @Override
  public Long getOrgIdById(Long id) {
    return this.baseMapper.getOrgIdById(id);
  }

  /**
   * 通过成本月报主键查询组织内码列表
   */
  @Override
  public List<Long> getOrgIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrgIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (Long) stringObjectMap.get("orgId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 成本月报的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public MonthlyCostReportRealVo getVoById(Long id) throws Exception {
    MonthlyCostReportRealVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询成本月报
   * @param search 查询条件
   * @return 成本月报分页查询结果
   */
  @Override
  public Page<MonthlyCostReportRealItemVo> pageSearch(
    MonthlyCostReportRealSearchParamPo search
  ) {
    Page<MonthlyCostReportRealItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(MonthlyCostReportRealItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 成本月报快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'MonthlyCostReportRealOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<MonthlyCostReportRealItemVo>> searchOptions(
    MonthlyCostReportRealSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询成本月报
   * @param search 查询条件
   * @return 成本月报列表查询结果
   */
  @Override
  public List<MonthlyCostReportRealItemVo> search(
    MonthlyCostReportRealSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询成本月报最后更新时间
   * @param search 查询条件
   * @return 成本月报最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(MonthlyCostReportRealSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 结转
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了结转操作"
  )
  @Override
  public void carryOver() throws Exception {
    if (monthlyCostReportRealCarryOverAction == null) {
      throw new Exception("此操作当前不可用");
    }
    monthlyCostReportRealCarryOverAction.run();
  }
}
